using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Web.UI;
using Spring.Objects.Factory;

namespace Sedna.Core.Controller.Configurations
{
    public class ConvertDataTranslator: BaseDataTranslator, IInitializingObject
    {
        private Type targetType;

        private MethodInfo convertMethod;

        public Type TargetType
        {
            set { targetType = value; }
        }
        
        

        public void AfterPropertiesSet()
        {
            if (targetType!=typeof(Boolean)&&targetType!=typeof(Char)&&targetType!=typeof(SByte)
                &&targetType!=typeof(Byte)&&targetType!=typeof(Int16)&&targetType!=typeof(Int32)
                &&targetType!=typeof(Int64)&&targetType!=typeof(UInt16)&&targetType!=typeof(UInt32)
                &&targetType!=typeof(UInt64)&&targetType!=typeof(Single)&&targetType!=typeof(Double)
                &&targetType!=typeof(Decimal)&&targetType!=typeof(DateTime)&&targetType!=typeof(String))
            {
                throw new ControllerConfigurationException("This type is not supported");
            }


            convertMethod = GetConvertMethod();
        }

        
        public override object UnsafeTranslate(Control control, object value, Type targetType)
        {
            return convertMethod.Invoke(null, new object[] {value});        
        }
        
        private MethodInfo GetConvertMethod()
        {
            return typeof (Convert).GetMethod("To" + targetType.Name, BindingFlags.Public|BindingFlags.Static, null, new Type[]{typeof(object), typeof(IFormatProvider)}, null);
        }
        
        
    }
}
